import json
from handle.logger import logger
from handle.S2Redis import redis_client, sync_data_background
from object.models import Warehousing,ProductVariant
from object.database import db

def get_warehouses_list():
    return redis_client.get('warehousing')

def in_warehouses_SKU(SKU,Stock_num):
    try:
        variant_SKU=SKU
        up_variant=ProductVariant.query.filter_by(SKU=variant_SKU).all()
        up_variant[0].Stock+=Stock_num
        db.session.commit()
        try:
            sync_data_background()
            return True,up_variant[0].Stock
        except Exception as e:
            return False,None
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise
    
def out_warehouses_SKU(SKU,Stock_num):
    try:
        variant_SKU=SKU
        up_variant=ProductVariant.query.filter_by(SKU=variant_SKU).all()
        up_variant[0].Stock-=Stock_num
        db.session.commit()
        try:
            sync_data_background()
            return True,up_variant[0].Stock
        except Exception as e:
            return False,None
    except Exception as e:
        db.session.rollback()  # 回滚事务以防止部分插入
        logger.error(f"创建商品时发生错误：{e}")
        raise

